package com.han.gateway.filter;

import com.han.gateway.config.IgnoreValidateUrlConfig;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@AllArgsConstructor
public class ValidateTokenFilter implements GlobalFilter {

    private final WebClient webClient;
    private final IgnoreValidateUrlConfig ignoreValidateUrlConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = exchange.getRequest().getPath().value();
        if (ignoreValidateUrlConfig.ignore(path)) {
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        return webClient.get()
                .uri("lb://auth/validateToken")
                .header("token", token)
                .retrieve()
                .bodyToMono(Integer.class)
                .flatMap(uid -> {
                    ServerHttpRequest newRequest = request.mutate().headers((headers) -> headers.put("uid", List.of(String.valueOf(uid)))).build();
                    ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
                    newExchange.getAttributes().put("uid", uid);

                    return chain.filter(newExchange);
                }).doOnError(e -> System.out.println("校验token失败: " + e.getMessage()))
                .onErrorResume(e -> {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                    byte[] bytes = "校验token失败".getBytes(StandardCharsets.UTF_8);
                    DataBuffer buffer = response.bufferFactory().wrap(bytes);
                    return response.writeWith(Mono.just(buffer));
                });
    }
}
